package com.party.mobile.web.controller.crowdfundMultiple;

import com.google.common.base.Strings;
import com.party.authorization.annotation.Authorization;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.audio.Audio;
import com.party.core.model.crowdfund.*;
import com.party.core.model.system.TargetType;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.audio.IAudioService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.crowdfund.IEventGradationService;
import com.party.core.service.crowdfund.IProjectGradationService;
import com.party.core.service.crowdfund.IProjectInfoGradationService;
import com.party.core.service.system.ISysConfigService;
import com.party.mobile.biz.crowdfund.ProjectBizService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.biz.file.FileBizService;
import com.party.mobile.biz.order.payOrder.PayOrderFactory;
import com.party.mobile.web.annotation.VisitCollect;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.crowdfund.output.ProjectOutput;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.vdurmont.emoji.EmojiParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 众筹者  多场活动
 *
 * @Author: huangzequn
 * @Date: 2019/3/21 14:13
 */
@Controller
@RequestMapping(value = "crowdfund/project/multiple")
public class ProjectMultipleController {


    @Autowired
    private CurrentUserBizService currentUserBizService;

    @Autowired
    private ProjectBizService projectBizService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private FileBizService fileBizService;

    @Autowired
    private CosBizService cosBizService;

    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    @Autowired
    private IAudioService audioService;

    @Autowired
    private IEventGradationService eventGradationService;

    @Autowired
    private IProjectGradationService projectGradationService;

    @Autowired
    private IProjectInfoGradationService projectInfoGradationService;

    @Autowired
    private PayOrderFactory payOrderFactory;

    private static Logger logger = LoggerFactory.getLogger(ProjectMultipleController.class);

    /**
     * 获取众筹项目详情
     *
     * @param id 项目编号
     * @return 项目详情
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "getDetails")
    @VisitCollect(module = TargetType.ZC_ACTIVITY)
    public AjaxResult getDetails(String id, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();
        logger.info("进入个人详细页的方法了=====" + id);
        //验参
        if (Strings.isNullOrEmpty(id)) {
            ajaxResult.setErrorCode(PartyCode.PARAMETER_ILLEGAL);
            ajaxResult.setDescription("众筹项目编号不能为空");
            return ajaxResult;
        }

        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        ProjectInfoGradation byProjectId = projectInfoGradationService.findByProjectId(id);
        ProjectOutput projectOutput = null;
        try {
            if (byProjectId == null) {
                throw new BusinessException(PartyCode.IS_NO_DATA, "该众筹是单场活动的");
            }
            projectOutput = projectBizService.getDetails(id, currentUser);
            if (StringUtils.isNotEmpty(projectOutput.getDeclaration())) {
                if (sysConfigService.isConvertBase64()) {
                    projectOutput.setDeclaration(StringUtils.decodeBase64New(projectOutput.getDeclaration()));
                } else {
                    projectOutput.setDeclaration(EmojiParser.parseToUnicode(projectOutput.getDeclaration()));
                }
            }
        } catch (BusinessException be) {
            ajaxResult.setErrorCode(be.getCode());
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            ajaxResult.setDescription("获取详情异常");
            return ajaxResult;
        }
        Activity activity = activityService.get(projectOutput.getTargeId());
        //二维码
        String filePath = fileBizService.getUploadCIPath("crowdfund", projectOutput.getAuthorId());
        String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + projectOutput.getId());
        projectOutput.setQrcodeUrl(qrCodeUrl);
        CrowdfundEvent crowdfundEvent = crowdfundEventService.getCorwdfundByActivityId(projectOutput.getTargeId());
        projectOutput.setPersonalRanking(crowdfundEvent.getPersonalRanking());
        projectOutput.setPersonalPopularPageState(activity.getPersonalPopularPageState());


        /** 当前系统时间在哪个阶段*/
        EventGradation ongoingGradation = eventGradationService.findOngoingGradation(crowdfundEvent.getId());
        if (null == ongoingGradation) {
            //最后阶段主题
            ongoingGradation = eventGradationService.getTheLastGradation(crowdfundEvent.getId());
        }

        /** zc_project_info表中正在进行哪个阶段*/
        ProjectGradation projectGradation1 = projectGradationService.get(byProjectId.getProjectGradationId());
        EventGradation eventGradation1 = eventGradationService.get(projectGradation1.getEventGradationId());
        /** 如果当前系统的阶段大于zc_project_info表中正在进行的阶段 就修改zc_project_info
         * 出现这种的情况是：如果众筹者在第一个阶段没有筹满 但是系统时间到了第二阶段
         * 这种情况要处理金额自动转入下一个阶段的流程
         */
        if (ongoingGradation.getGradation() > eventGradation1.getGradation()) {
            Project project = new Project();
            project.setCreateDate(projectOutput.getCreateDate());
            project.setId(projectOutput.getId());
            project.setAuthorId(projectOutput.getAuthorId());
            project.setActualAmount(projectOutput.getActualAmount());
            project.setPayType(projectOutput.getPayType());
            payOrderFactory.automaticShift(ongoingGradation,project,activity);
        }



        /** 最后一个阶段的主题*/
        EventGradation theLastEventGradation = eventGradationService.getTheLastGradation(crowdfundEvent.getId());
        ProjectGradation theLastProjectGradation = projectGradationService.getByEventGradationId(theLastEventGradation.getId(), id);
        if (theLastProjectGradation.getUseTime() > 0) {
            projectOutput.setChallengeShow(YesNoStatus.YES.getCode());
        } else {
            projectOutput.setChallengeShow(YesNoStatus.NO.getCode());
        }

        Map<String, Object> params = new HashMap<>();
        boolean equals = currentUser.getId().equals(projectOutput.getAuthorId());
        /** 根据projectId 找到当前众筹者正在众筹哪个阶段*/
        EventGradation eventGradation = eventGradationService.getOngoingGradation(id);
        List<ProjectGradation> projectGradationList = new ArrayList<>();
        if (ProjectInfoGradation.CHALLENGESTATE_STOP.equals(eventGradation.getChallengeState())) {
            List<ProjectGradation> successListForProjectId = projectGradationService.getSuccessListForProjectId(id);
            ProjectGradation projectGradation = successListForProjectId.get(0);
            EventGradation eventGradation2 = eventGradationService.get(projectGradation.getEventGradationId());
            /** 如果说是停止挑战*/
            /** 上一阶段的目标金额*/
            projectOutput.setTargetAmount(projectGradation.getTargetAmount().floatValue());
            /** 上一阶段的活动时间*/
            projectOutput.setEndTime(eventGradation2.getEndTime());
            /** 当前众筹者是否继续挑战*/
            projectOutput.setChallengeState(eventGradation.getChallengeState());
            /** 上一阶段的已筹金额*/
            projectOutput.setActualAmount(projectGradation.getTargetAmount().floatValue());
            params.put("projectId", id);
            params.put("endTime", eventGradation2.getEndTime());
            projectGradationList = projectGradationService.getProjectGradationByTargetId(params);
            /** 如果是停止挑战了，则众筹成功了*/
            projectOutput.setIsSuccess(YesNoStatus.YES.getCode());
            /** 当前众筹者当前正在筹第几阶段*/
            projectOutput.setGradation(eventGradation2.getGradation());
        }


        if (eventGradation.getChallengeState() == ProjectInfoGradation.CHALLENGESTATE_RUN) {
            params.put("projectId", id);
            params.put("endTime", eventGradation.getEndTime());
            projectGradationList = projectGradationService.getProjectGradationByTargetId(params);
            if (projectGradationList.size() > 0) {
                Double consumptionMoney = 0.00;
                for (ProjectGradation projectGradation : projectGradationList) {
                    consumptionMoney += projectGradation.getTargetAmount();
                    projectGradation.setPercentage(1);
                }
                /** 当前阶段的累计金额*/
                float sub = BigDecimalUtils.sub(projectOutput.getActualAmount(), consumptionMoney.floatValue());
                projectOutput.setActualAmount(BigDecimalUtils.round(sub, 2));
            }
            /** 当前阶段的目标金额*/
            projectOutput.setTargetAmount(eventGradation.getPrice().floatValue());
            /** 当前阶段的活动时间*/
            projectOutput.setEndTime(eventGradation.getEndTime());
            /** 当前众筹者是否继续挑战*/
            projectOutput.setChallengeState(eventGradation.getChallengeState());
            /** 当前众筹者当前正在筹第几阶段*/
            projectOutput.setGradation(eventGradation.getGradation());
        }
        if (equals) {
            projectOutput.setProjectGradationList(projectGradationList);
            if (projectGradationList.size() > 0 || eventGradation.getChallengeState() == ProjectInfoGradation.CHALLENGESTATE_STOP) {
                //自己进自己的众筹详情页
                projectOutput.setView(YesNoStatus.YES.getCode());
            } else {
                projectOutput.setView(YesNoStatus.NO.getCode());
            }

        } else {
            projectGradationList.removeAll(projectGradationList);
            projectOutput.setProjectGradationList(projectGradationList);
            projectOutput.setView(YesNoStatus.NO.getCode());
        }

        if (1 == activity.getPersonalPopularPageState()) {
            //1代表显示该项目报名人员
            projectOutput.setTeamName(activity.getPublisher());
        }
        if (0 == activity.getPersonalPopularPageState()) {
            //0代表显示所属主题报名人员
            projectOutput.setTeamName("同行队友");
        }
        if (3 == activity.getPersonalPopularPageState()) {
            //3代表显示该项目报名人员的支持者
            projectOutput.setTeamName("支持者");
        }
        if (0 == crowdfundEvent.getStrategyState()) {
            //显示众筹攻略
            if (equals) {
                //如果登入人和报名人不是同一个人，就不显示众筹攻略
                projectOutput.setStrategyState(0);
            } else {
                projectOutput.setStrategyState(1);
            }
        } else {
            projectOutput.setStrategyState(1);
        }
        // 众筹项目详情二维码
        String targetFilePath = fileBizService.getUploadCIPath(activity.getMember(), "zcActivity");
        String detailFileName = "detail_" + activity.getId();
        String detailQrCodeUrl = cosBizService.getPreviewPictureUrl(targetFilePath + detailFileName);
        projectOutput.setTargetQrCode(detailQrCodeUrl);


        //是否播放音乐(0否/是)
        Integer isPlayMusic = 0;
        //音频url
        String audioUrl = "";
        try {
            Audio audio = audioService.findAudioByEventId(activity.getEventId());
            if (null != audio) {
                isPlayMusic = 1;
                audioUrl = audio.getAudioUrl();
            }
        } catch (Exception e) {
            logger.info("众筹项目详情页H5,音频获取失败", e.getMessage());
        }
        projectOutput.setIsPlayMusic(isPlayMusic);
        projectOutput.setAudioUrl(audioUrl);
        return AjaxResult.success(projectOutput);
    }

    /***
     * 更新挑战状态
     * @param projectId
     * @return
     */
    @RequestMapping("updateChallengeStatus")
    @ResponseBody
    public AjaxResult updateChallengeStatus(String projectId, Integer challengeState) {
        try {
            ProjectInfoGradation projectInfoGradation = projectInfoGradationService.findByProjectId(projectId);
            projectInfoGradation.setChallengeState(challengeState);
            projectInfoGradationService.update(projectInfoGradation);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("更新挑战状态异常", e);
            return AjaxResult.error();
        }

    }

}
